<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
</head>
<body>
<script>
    var socket;
    if(window.WebSocket){
        socket = new WebSocket("wss://k8s-horse-gateway.mashibing.cn/ws?client=yan_xuan&ticket=" + urlencode('pLnzSnEhMut+i0DvlDeBXp3AnVVmQAdoDmVmA3es5hZRskNO94+SONrhKbqD4lmC') + "&connect=2&user=87&nickname=%E7%BD%97%E4%BC%AF%E7%89%B9&avatar=https%3A%2F%2Fmsb-edu-dev.oss-cn-beijing.aliyuncs.com%2Fuc%2Faccount-avatar%2F6B12CFC0-C44A-4144-8769-77CA8483B42B.jpeg");

        socket.onmessage = function (event) {

            var ta = document.getElementById("responseText");
            var data = event.data;
			var a = JSON.parse(data);
			if (a.content != null && !a.content.hasOwnProperty('text')) {
				ta.value = ta.value+"\n"+data;
			}
        }

        socket.onopen = function(event){
            var ta = document.getElementById("responseText");
            ta.value="连接开启";
            var param = '{"traceId":"uuid","traceType": "26"}';
            setInterval(() => {send(param)}, 3000);
        }
        socket.onclose= function (event){
            var ta = document.getElementById("responseText");
            ta.value=ta.value+"\n"+"连接断开";
        }
    }else{
        alert("浏览器不支持WebSocket");
    }
    function send(messageDTO){
        if(!window.WebSocket){
            return;
        }
        if(socket.readyState == WebSocket.OPEN || true) {
            socket.send(messageDTO);
        }else{
            alert("连接尚未开启");
        }
    }
	
	function urlencode (str) {  
    str = (str + '').toString();   

    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').  
    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
    }
</script>
<form onsubmit="return false">
    <textarea name="messageDTO" style="width:400px;height:200px"></textarea>

    <input type="button" value="发送数据" onclick="send(this.form.messageDTO.value)">

    <h3>服务端输出：</h3>

    <textarea id="responseText" style="width:400px; height:300px"></textarea>

    <input onclick="document.getElementById('responseText').value=''" type="button" value="清空内容">
</form>
</body>
</html>
